package org.lynn.ws.websocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;


/**
 *初始化连接时的各个组件
 * @author gy
 * @date 2019/3/2 7:47
 */
public class WebSocketChannelHandler extends ChannelInitializer<SocketChannel>{

    /**
     * 读超时
     */
    private static final int READ_IDEL_TIME_OUT = 4;
    /**
     * 写超时
     */
    private static final int WRITE_IDEL_TIME_OUT = 5;
    /**
     * 所有超时
     */
    private static final int ALL_IDEL_TIME_OUT = 7;




    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        // 编解码使用
        socketChannel.pipeline().addLast("http-codec",new HttpServerCodec());
        // 处理post message body
        socketChannel.pipeline().addLast("aggregator",new HttpObjectAggregator(65536));
        // 服务器生成HTTP响应时，不好确定响应数据的大小，一般就使用chunked编码进行传输
        socketChannel.pipeline().addLast("http-chunked",new ChunkedWriteHandler());

        socketChannel.pipeline().addLast(new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.HOURS));

        socketChannel.pipeline().addLast("handler",new WebSocketHandler());

        socketChannel.pipeline().addLast(new WebSocketHandler());

    }
}
